package com.hollycrm.unicom.sheet.code.web;

import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.beanutils.PropertyUtils;
import com.hollycrm.springframework.factory.DefaultBeanFactory;
import com.hollycrm.unicom.sheet.BeanResource;
import com.hollycrm.unicom.sheet.code.CodeManager;
import com.hollycrm.unicom.sheet.define.SheetCategory;

/**
 * SheetCategoryLabelTag
*
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author Tian Kai
 * @version 1.0
 */
public class SheetCategoryLabelTag extends BodyTagSupport {

    private Object nameBean;
    private String name;
    private String categoryKey;
    private String categoryKeyProperty;

    public int doStartTag() throws JspException {

        SheetCategory category = null;
        CodeManager codeManager = (CodeManager) DefaultBeanFactory.getBean(BeanResource.CODE_MANAGER);

        if (categoryKey != null) {
            category = codeManager.getSheetCategory(categoryKey);
        }
        else {
            nameBean = pageContext.findAttribute(name);
            if (nameBean == null) throw new JspException("not find bean: " + name + " in any scope.");
            try {
                if (nameBean instanceof String)
                    category = codeManager.getSheetCategory((String) nameBean);
                else
                    category = codeManager.getSheetCategory( (String)
                        PropertyUtils.getProperty(nameBean, categoryKeyProperty));
            }
            catch (Exception ex) {
                throw new JspException("tag categoryKeyProperty: " +
                                       categoryKeyProperty + ex.getMessage());
            }
        }

        if (category != null) {
            try {
                pageContext.getOut().print(category.getCategoryName() == null ?
                                             "" : category.getCategoryName());
            }
            catch (IOException ex1) {
                throw new JspException(ex1);
            }
        }

        return (SKIP_BODY);
    }

    public void release() {
        super.release();
        nameBean = null;
        name = null;
        categoryKey = null;
        categoryKeyProperty = null;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCategoryKey() {
        return categoryKey;
    }
    public void setCategoryKey(String categoryKey) {
        this.categoryKey = categoryKey;
    }
    public String getCategoryKeyProperty() {
        return categoryKeyProperty;
    }
    public void setCategoryKeyProperty(String categoryKeyProperty) {
        this.categoryKeyProperty = categoryKeyProperty;
    }


}
